<template>
  <div class="chat-window">
    <!-- 加载提示 -->
    <div 
      v-if="loading" 
      class="loading-overlay"
      v-loading="loading"
      element-loading-text="正在加载对话配置..."
      element-loading-background="rgba(0, 0, 0, 0.8)"
    >
    </div>

    <!-- 聊天界面 -->
    <div v-if="!loading && dialogConfig" class="chat-container">
      <!-- 标题栏 -->
      <div class="chat-header">
        <div class="header-info">
          <el-icon><ChatDotRound /></el-icon>
          <span class="title">AI助手</span>
          <!-- 场景选择器 -->
          <div class="header-scene-selector">
            <span class="scene-separator">-</span>
            <el-select
              v-model="selectedSceneId"
              placeholder="选择场景"
              clearable
              filterable
              size="small"
              class="scene-select"
              @change="onSceneChange"
              :teleported="false"
            >
              <el-option
                v-for="scene in sceneOptions"
                :key="scene.scene_id"
                :label="scene.scene_name"
                :value="scene.scene_id"
              />
            </el-select>
          </div>
        </div>
        
        <!-- 标题栏右侧控制按钮 -->
        <div class="header-controls">
          <!-- 清屏按钮 -->
          <el-button
            type="warning"
            @click="clearScreen"
            size="small"
            circle
            class="header-clear-btn"
            title="清空对话记录"
          >
            <el-icon><Delete /></el-icon>
          </el-button>
          
          <!-- TTS开关按钮 -->
          <el-button
            :type="isTTSEnabled ? 'success' : 'info'"
            @click="toggleTTS"
            @contextmenu.prevent="showTTSSettingsMenu"
            size="small"
            circle
            class="header-tts-btn"
            :title="isTTSEnabled ? 'TTS已启用 - 点击禁用，右键设置' : 'TTS已禁用 - 点击启用，右键设置'"
          >
            <el-icon><VideoPlay /></el-icon>
          </el-button>
          
          <!-- TTS播放指示器 -->
          <span v-if="isPlayingTTS" class="header-tts-indicator">🎵</span>
        </div>
      </div>

      <!-- 消息列表 -->
      <div class="message-list" ref="messageListRef">
        <div
          v-for="(message, index) in messages"
          :key="index"
          :class="['message-item', message.type, message.messageType]"
        >
          <div class="message-content" :data-final="message.data?.isFinalResult ? 'true' : 'false'">
            <!-- 消息图标 -->
            <div v-if="message.type === 'assistant'" class="message-icon">
              <el-icon v-if="message.messageType === 'thinking'" class="icon-thinking">
                <ChatDotRound />
              </el-icon>
              <el-icon v-else-if="message.messageType === 'tool'" class="icon-tool">
                <Tools />
              </el-icon>
              <el-icon v-else-if="message.messageType === 'rag'" class="icon-rag">
                <Document />
              </el-icon>
              <el-icon v-else-if="message.messageType === 'mcp'" class="icon-mcp">
                <Connection />
              </el-icon>
              <el-icon v-else-if="message.messageType === 'human_interaction'" class="icon-interaction">
                <User />
              </el-icon>
              <el-icon v-else-if="message.messageType === 'error'" class="icon-error">
                <Warning />
              </el-icon>
              <el-icon v-else class="icon-assistant">
                <ChatDotRound />
              </el-icon>
            </div>
            
            <div class="message-text">
              <!-- 思考消息 -->
              <span v-if="message.messageType === 'thinking'" class="thinking-text">
                <span v-html="formatMessage(message.content)"></span>
              </span>
              
              <!-- 工具消息 -->
              <span v-else-if="message.messageType === 'tool'" class="tool-text">
                <span v-html="formatMessage(message.content)"></span>
                <div v-if="message.data?.tool_result" class="tool-result-section">
                  <el-button 
                    size="small" 
                    type="primary" 
                    plain 
                    @click="toggleResultDisplay(index, 'tool')"
                    class="result-toggle-btn"
                  >
                    {{ message.showResult ? '隐藏结果' : '查看工具结果' }}
                  </el-button>
                  <div v-if="message.showResult" class="result-content">
                    <pre>{{ JSON.stringify(message.data.tool_result, null, 2) }}</pre>
                  </div>
                </div>
                <!-- 保留原有的llm_result显示逻辑 -->
                <div v-if="message.data?.llm_result" class="tool-data">
                  <details>
                    <summary>查看返回结果</summary>
                    <pre>{{ JSON.stringify(message.data.llm_result, null, 2) }}</pre>
                  </details>
                </div>
              </span>
              
              <!-- RAG消息 -->
              <span v-else-if="message.messageType === 'rag'" class="rag-text">
                <span v-html="formatMessage(message.content)"></span>
                <div v-if="message.data?.count" class="rag-info">
                  检索到 {{ message.data.count }} 条相关信息
                </div>
                <div v-if="message.data?.rag_results" class="rag-result-section">
                  <el-button 
                    size="small" 
                    type="success" 
                    plain 
                    @click="toggleResultDisplay(index, 'rag')"
                    class="result-toggle-btn"
                  >
                    {{ message.showResult ? '隐藏结果' : '查看RAG结果' }}
                  </el-button>
                  <div v-if="message.showResult" class="result-content">
                    <pre>{{ JSON.stringify(message.data.rag_results, null, 2) }}</pre>
                  </div>
                </div>
                <!-- 保留原有的llm_result显示逻辑 -->
                <div v-if="message.data?.llm_result" class="rag-data">
                  <details>
                    <summary>查看返回结果</summary>
                    <pre>{{ JSON.stringify(message.data.llm_result, null, 2) }}</pre>
                  </details>
                </div>
              </span>
              
              <!-- MCP消息 -->
              <span v-else-if="message.messageType === 'mcp'" class="mcp-text">
                <span v-html="formatMessage(message.content)"></span>
                <div v-if="message.data?.mcp_result" class="mcp-result-section">
                  <el-button 
                    size="small" 
                    type="info" 
                    plain 
                    @click="toggleResultDisplay(index, 'mcp')"
                    class="result-toggle-btn"
                  >
                    {{ message.showResult ? '隐藏结果' : '查看MCP结果' }}
                  </el-button>
                  <div v-if="message.showResult" class="result-content">
                    <pre>{{ JSON.stringify(message.data.mcp_result, null, 2) }}</pre>
                  </div>
                </div>
                <!-- 保留原有的llm_result显示逻辑 -->
                <div v-if="message.data?.llm_result" class="mcp-data">
                  <details>
                    <summary>查看返回结果</summary>
                    <pre>{{ JSON.stringify(message.data.llm_result, null, 2) }}</pre>
                  </details>
                </div>
              </span>
              
              <!-- 人机交互消息 -->
              <span v-else-if="message.messageType === 'human_interaction'" class="interaction-text">
                <div class="interaction-content">
                  <div class="interaction-question">
                    <span v-html="formatMessage(message.content)"></span>
                  </div>
                  
                  <!-- 等待响应提示 -->
                  <div v-if="!message.data?.responded" class="interaction-waiting">
                    <el-tag type="warning" size="small" effect="plain">
                      ⏳ 等待您的响应...
                    </el-tag>
                  </div>
                  
                  <!-- 响应结果 -->
                  <div v-else class="interaction-result">
                    <el-tag :type="message.data.approved ? 'success' : 'danger'" size="small">
                      {{ message.data.approved ? '✓ 已确认执行' : '✗ 已取消执行' }}
                    </el-tag>
                  </div>
                </div>
              </span>
              
              <!-- 错误消息 -->
              <span v-else-if="message.messageType === 'error'" class="error-text">
                <span class="error-indicator">⚠️</span>
                <span v-html="formatMessage(message.content)"></span>
              </span>
              
              <!-- 普通消息 -->
              <span v-else>
                <span v-html="formatMessage(message.content)"></span>
                <span v-if="message.partial" class="typing-cursor">|</span>
              </span>
            </div>
            
            <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-area">
        <!-- 快捷键帮助按钮 -->
        <div class="keyboard-help-container">
          <el-button
            size="small"
            type="info"
            plain
            @click="showKeyboardHelp"
            class="keyboard-help-btn"
            title="查看快捷键说明"
          >
            <el-icon><QuestionFilled /></el-icon>
            快捷键说明
          </el-button>
        </div>
        
        <!-- 文字输入区域 -->
        <div class="input-with-send">
          <!-- 文字输入 -->
          <div class="text-input">
            <el-input
              v-model="inputText"
              type="textarea"
              :rows="2"
              :placeholder="isInInteractionMode ? '请输入您对此操作的补充说明或意见...' : '请输入您的问题...'"
              @keydown="handleKeyDown"
              :class="{ 'interaction-input': isInInteractionMode }"
            />
            
            <!-- 人机交互提示 -->
            <div v-if="isInInteractionMode" class="interaction-prompt">
              <el-icon class="prompt-icon"><User /></el-icon>
              <span class="prompt-text">
                您可以在输入框中输入补充说明或新的问题。
              </span>
            </div>
            
            <!-- 实时识别文本提示 -->
            <div v-if="currentRecognitionText" class="recognition-preview">
              <span class="recognition-label">正在识别:</span>
              <span class="recognition-text">{{ currentRecognitionText }}</span>
            </div>
            

            <div class="input-actions">
              <!-- 语音输入按钮 -->
              <el-button
                :type="getVoiceButtonType()"
                @click="toggleRecording"
                size="small"
                circle
                class="voice-btn"
                :loading="isConnectingAudio"
                :disabled="!audioSupport.supported || isInInteractionMode"
                title="语音输入"
              >
                <el-icon><Microphone /></el-icon>
              </el-button>
              
              <span v-if="isRecording" class="recording-indicator">●</span>
            </div>
          </div>

          <!-- 发送按钮 -->
          <div v-if="!isInInteractionMode" class="send-button">
            <el-button type="primary" @click="sendMessage" :disabled="!inputText.trim()">
              发送
            </el-button>
          </div>
          
          <!-- 人机交互响应按钮 -->
          <div v-else class="interaction-buttons">
            <el-button 
              type="success" 
              @click="respondToInteraction(true)"
              :disabled="!currentInteractionId"
            >
              <el-icon><Check /></el-icon>
              确认执行
            </el-button>
            <el-button 
              type="danger" 
              @click="respondToInteraction(false)"
              :disabled="!currentInteractionId"
            >
              <el-icon><Close /></el-icon>
              取消执行
            </el-button>
          </div>
        </div>
      </div>

      <!-- 自定义按钮 -->
      <div v-if="dialogConfig.buttons.length" class="custom-buttons">
        <el-button
          v-for="button in dialogConfig.buttons"
          :key="button.id"
          :type="button.type"
          size="small"
          @click="handleButtonClick(button)"
        >
          {{ button.text }}
        </el-button>
      </div>
    </div>

    <!-- 使用新的TTS设置组件 -->
    <TTSSettings 
      v-model="showTTSSettings"
      :settings="ttsSettings"
      storage-key="tts-settings"
      @settings-changed="handleTTSSettingsChanged"
    />

    <!-- 错误状态 -->
    <div v-if="!loading && !dialogConfig" class="error-container">
      <el-result
        icon="error"
        title="加载失败"
        sub-title="无法加载对话框配置"
      >
        <template #extra>
          <el-button type="primary" @click="reloadConfig">重新加载</el-button>
        </template>
      </el-result>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  ChatDotRound, Microphone, Tools, Document, Warning, Connection, User, Check, Close, VideoPlay, Delete, QuestionFilled, RefreshLeft
} from '@element-plus/icons-vue'
import { marked } from 'marked'
import { dialogApi, sceneApi } from '@/api/scene'
import { agentApi } from '@/api/agent'
// 导入音频工具类
import { 
  AudioRecognitionClient, 
  AudioRecognitionResult, 
  AudioRecognitionConfig,
  checkAudioSupport,
  generateSessionId 
} from '@/utils/audioUtils'
// 添加音频API导入
import axios from 'axios'
// 导入语音指令处理器
import { VoiceCommandHandler, type VoiceCommandHandlerConfig } from '@/utils/voiceCommandHandler'
// 导入键盘帮助工具
import { KeyboardHelpUtils } from '@/utils/KeyboardHelpUtils'
import TTSSettings from './TTSSettings.vue'

// 配置marked选项
marked.setOptions({
  gfm: true, // 启用GitHub风格的markdown
  breaks: true, // 支持换行符转换为<br>
  pedantic: false, // 不严格遵循原始markdown规范
})

// 使用marked库格式化消息内容
const formatMessage = (content: string): string => {
  try {
    // 使用marked.parse并确保返回字符串
    const result = marked.parse(content, { async: false })
    return result as string
  } catch (error) {
    console.error('Markdown解析错误:', error)
    // 如果解析失败，返回原始内容并进行基础转义
    return content.replace(/\n/g, '<br>')
  }
}

// 类型定义
interface DialogSize {
  width: number
  height: number
}

interface ButtonConfig {
  id: string
  text: string
  type: string
  action: string
}

interface DialogConfig {
  id: number
  scene_id: string
  dialog_size: DialogSize
  transparency: number
  buttons: ButtonConfig[]
}

interface Message {
  type: 'user' | 'assistant'
  content: string
  timestamp: Date
  messageType?: 'message' | 'thinking' | 'tool' | 'rag' | 'error' | 'mcp' | 'human_interaction'  // 添加human_interaction类型
  data?: any  // 新增数据字段
  partial?: boolean  // 是否为部分消息
  showResult?: boolean  // 是否显示结果详情
}

interface TTSConfig {
  model?: string
  volume?: number
  speechRate?: number
  pitchRate?: number
}

// 响应式数据
const loading = ref(true)
const dialogConfig = ref<DialogConfig | null>(null)
const messages = ref<Message[]>([])
const inputText = ref('')
const isRecording = ref(false)
const messageListRef = ref<HTMLElement>()

// 人机交互状态
const currentInteractionId = ref<string | null>(null)
const isInInteractionMode = ref(false)

// 音频识别相关
const audioClient = ref<AudioRecognitionClient | null>(null)
const audioStatus = ref<'disconnected' | 'connecting' | 'connected' | 'recording' | 'stopped' | 'error'>('disconnected')
const audioSupport = ref(checkAudioSupport())
const currentRecognitionText = ref('')
const isConnectingAudio = ref(false)

// TTS 语音合成相关
const isTTSEnabled = ref(false)  // TTS功能开关
const ttsSettings = ref({
  model: 'sambert-zhijia-v1',  // 默认使用知佳
  volume: 50,
  speechRate: 1.0,
  pitchRate: 1.0
})
const isPlayingTTS = ref(false)  // 是否正在播放TTS
const currentAudio = ref<HTMLAudioElement | null>(null)  // 当前播放的音频元素

// TTS设置相关
const showTTSSettings = ref(false)  // 是否显示TTS设置菜单

// 场景选择相关
const selectedSceneId = ref<string>('')  // 当前选中的场景ID
const sceneOptions = ref<Array<{scene_id: string, scene_name: string}>>([])  // 场景选项列表
const loadingScenes = ref(false)  // 是否正在加载场景列表

// 语音指令处理器
let voiceCommandHandler: VoiceCommandHandler | null = null

// 调试：打印音频支持检查结果
console.log('音频支持检查结果:', audioSupport.value)

// 音频API辅助方法
const audioAPI = {
  // 关闭音频会话
  async closeSession(sessionId: string) {
    try {
      const response = await axios.delete(`/api/audio/sessions/${sessionId}`)
      return response.data
    } catch (error) {
      console.error('关闭音频会话API调用失败:', error)
      throw error
    }
  },
  
  // 获取活跃会话列表
  async getActiveSessions() {
    try {
      const response = await axios.get('/api/audio/sessions')
      return response.data
    } catch (error) {
      console.error('获取音频会话列表失败:', error)
      throw error
    }
  },

  // TTS 相关API
  tts: {
    // 文本转语音 (返回Base64数据)
    async synthesizeToBase64(text: string, config: TTSConfig = {}) {
      try {
        const params = new URLSearchParams()
        params.append('text', text)
        params.append('model', config.model || ttsSettings.value.model)
        params.append('volume', String(config.volume || ttsSettings.value.volume))
        params.append('speech_rate', String(config.speechRate || ttsSettings.value.speechRate))
        params.append('pitch_rate', String(config.pitchRate || ttsSettings.value.pitchRate))
        params.append('format', 'wav')
        params.append('sample_rate', '48000')

        const response = await axios.post('/api/audio/tts/synthesize/base64', params, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        })
        return response.data
      } catch (error) {
        console.error('TTS合成失败:', error)
        throw error
      }
    }
  }
}

// 方法
const loadDialogConfig = async () => {
  try {
    loading.value = true
    const urlParams = new URLSearchParams(window.location.search)
    const sceneId = urlParams.get('scene_id') || 'ada5d384-ed0d-44e5-bbbe-1173c8dc2830'
    
    const response = await dialogApi.getDialogByScene(sceneId)
    dialogConfig.value = response
    
    // 初始化欢迎消息
    messages.value.push({
      type: 'assistant',
      content: `您好！我是AI助手，有什么可以帮助您的吗？`,
      timestamp: new Date()
    })
    
    // 设置窗口透明度
    if (response.transparency < 100) {
      document.body.style.opacity = (response.transparency / 100).toString()
    }
    loadSceneOptions()
  } catch (error) {
    console.error('加载对话框配置失败:', error)
    ElMessage.error('加载配置失败')
  } finally {
    loading.value = false
  }
}

const reloadConfig = () => {
  loadDialogConfig()
  loadSceneOptions()
}

// 场景选择相关方法
const loadSceneOptions = async () => {
  try {
    loadingScenes.value = true
    const currentSceneId = dialogConfig.value?.scene_id
    
    if (!currentSceneId) {
      console.warn('当前没有场景ID，跳过加载场景选项')
      sceneOptions.value = []
      return
    }
    
    // 同时获取父场景和子场景
    const [parentScenes, childScenes] = await Promise.allSettled([
      // 获取当前场景的祖先节点（父场景路径）
      sceneApi.getAncestors(currentSceneId).catch(() => []),
      // 获取当前场景的子场景
      sceneApi.getChildren(currentSceneId).catch(() => [])
    ])
    
    const allScenes = []
    
    // 添加祖先场景（父场景）
    if (parentScenes.status === 'fulfilled' && parentScenes.value.length > 0) {
      const ancestors = parentScenes.value.map((scene: any) => ({
        scene_id: scene.scene_id,
        scene_name: `↑ ${scene.scene_name}`, // 添加箭头标识父场景
        is_parent: true
      }))
      allScenes.push(...ancestors)
    }
    
    // 添加当前场景
    try {
      const currentScene = await sceneApi.getSceneById(currentSceneId)
      allScenes.push({
        scene_id: currentScene.scene_id,
        scene_name: `● ${currentScene.scene_name}`, // 添加圆点标识当前场景
        is_current: true
      })
    } catch (error) {
      console.warn('获取当前场景信息失败:', error)
    }
    
    // 添加子场景
    if (childScenes.status === 'fulfilled' && childScenes.value.length > 0) {
      const children = childScenes.value.map((scene: any) => ({
        scene_id: scene.scene_id,
        scene_name: `↓ ${scene.scene_name}`, // 添加箭头标识子场景
        is_child: true
      }))
      allScenes.push(...children)
    }
    
    sceneOptions.value = allScenes
    console.log('场景选项加载完成:', allScenes)
    
    // 设置当前场景为选中状态
    if (!selectedSceneId.value && currentSceneId) {
      selectedSceneId.value = currentSceneId
    }
    
  } catch (error) {
    console.error('加载场景选项失败:', error)
    ElMessage.error('加载场景选项失败')
  } finally {
    loadingScenes.value = false
  }
}

const onSceneChange = (sceneId: string) => {
  console.log('场景切换:', sceneId)
  selectedSceneId.value = sceneId
  // 可以在这里添加场景切换后的其他处理逻辑
}

// 清屏方法 - 清除所有对话内容，只保留欢迎消息
const clearScreen = () => {
  messages.value = [{
    type: 'assistant',
    content: `您好！我是AI助手，有什么可以帮助您的吗？`,
    timestamp: new Date()
  }]
  
  // 滚动到底部
  nextTick(() => {
    scrollToBottom()
  })
}

const sendMessage = async () => {
  if (!inputText.value.trim()) return

  // 添加用户消息
  messages.value.push({
    type: 'user',
    content: inputText.value,
    timestamp: new Date()
  })

  const userMessage = inputText.value
  inputText.value = ''

  // 滚动到底部
  await nextTick()
  scrollToBottom()

  // 记录当前助手消息的索引
  let currentAssistantMessageIndex = -1
  let isStreamComplete = false

  try {
    // 使用流式接口，传递当前选中的scene_id
    await agentApi.sendMessageStream(userMessage, undefined, (streamData: any) => {
      handleStreamMessage(streamData)
    }, selectedSceneId.value)
    
  } catch (error) {
    console.error('发送消息失败:', error)
    
    // 如果流式请求失败，回退到普通请求
    try {
      messages.value.push({
          type: 'assistant',
          content: `抱歉，处理您的消息时遇到问题：${error || '未知错误'}`,
          timestamp: new Date(),
          messageType: 'error'
        })
    } catch (fallbackError) {
      console.error('备用请求也失败:', fallbackError)
      messages.value.push({
        type: 'assistant',
        content: '抱歉，网络连接出现问题，请稍后重试。',
        timestamp: new Date(),
        messageType: 'error'
      })
      
      ElMessage.error('发送消息失败，请检查网络连接')
    }
  }

  // 最终滚动到底部
  scrollToBottom()
}

const toggleRecording = async () => {
  if (!audioSupport.value.supported) {
    ElMessage.error(`浏览器不支持音频录制：${audioSupport.value.issues.join(', ')}`)
    return
  }

  if (isRecording.value) {
    // 停止录音 - 现在是async方法
    await stopRecording()
  } else {
    // 开始录音
    await startRecording()
  }
}

const startRecording = async () => {
  try {
    isConnectingAudio.value = true
    
    // 如果没有音频客户端，创建一个
    if (!audioClient.value) {
      await initializeAudioClient()
    }
    
    // 如果客户端未连接，先连接
    if (audioClient.value && audioClient.value.getConnectionStatus() !== 'connected') {
      await audioClient.value.connect()
    }
    
    // 发送开始录音控制消息（让后端处理麦克风）
    if (audioClient.value) {
      await audioClient.value.sendControlMessage({
        type: 'start_recording'
      })
      ElMessage.success('🎤 后端开始录音，请说话...')
    }
    
  } catch (error: any) {
    console.error('开始录音失败:', error)
    ElMessage.error(`开始录音失败: ${error.message || '未知错误'}`)
    isRecording.value = false
    audioStatus.value = 'error'
  } finally {
    isConnectingAudio.value = false
  }
}

const stopRecording = async () => {
  console.log('🛑 开始停止录音...')
  
  // 获取当前的session ID
  const currentSessionId = audioClient.value?.getSessionId()
  
  // 发送停止录音控制消息
  if (audioClient.value) {
    await audioClient.value.sendControlMessage({
      type: 'stop_recording'
    })
    ElMessage.info('🔇 录音已停止')
  }
  
  // 调用后端API关闭session
  if (currentSessionId) {
    try {
      console.log(`🗑️ 关闭音频会话: ${currentSessionId}`)
      await audioAPI.closeSession(currentSessionId)
      console.log('✅ 音频会话已成功关闭')
    } catch (error) {
      console.error('❌ 关闭音频会话失败:', error)
      // 不显示错误消息给用户，因为这是后台操作
    }
  }
  
  // 手动重置所有相关状态，确保UI正确更新
  isRecording.value = false
  isConnectingAudio.value = false
  currentRecognitionText.value = ''
  
  // 停止录音后断开连接，需要重新连接才能再次使用
  audioStatus.value = 'disconnected'
  
  // 清理音频客户端
  if (audioClient.value) {
    audioClient.value.disconnect()
    audioClient.value = null
  }
  
  console.log('✅ 录音状态已重置', {
    isRecording: isRecording.value,
    isConnectingAudio: isConnectingAudio.value,
    audioStatus: audioStatus.value,
    currentRecognitionText: currentRecognitionText.value,
    sessionClosed: !!currentSessionId
  })
}

// 重置音频状态的辅助方法
const resetAudioState = () => {
  console.log('🔄 重置音频状态...')
  
  isRecording.value = false
  isConnectingAudio.value = false
  currentRecognitionText.value = ''
  
  // 如果有音频客户端且连接正常，保持连接状态
  if (audioClient.value && audioClient.value.getConnectionStatus() === 'connected') {
    audioStatus.value = 'connected'
  } else {
    audioStatus.value = 'disconnected'
  }
  
  console.log('✅ 音频状态已重置')
}

const initializeAudioClient = async () => {
  const sessionId = generateSessionId()
  
  // 配置现在由后端处理，前端只需要传递空配置或基本配置
  const config: AudioRecognitionConfig = {}

  audioClient.value = new AudioRecognitionClient(
    sessionId,
    config,
    handleAudioRecognitionResult,
    handleAudioError,
    handleAudioStatusChange
  )
}

const handleAudioRecognitionResult = async (result: AudioRecognitionResult) => {
  console.log('语音识别结果:', result)
  
  switch (result.type) {
    case 'recognition_result':
      if (result.text) {
        currentRecognitionText.value = result.text
        
        // 使用语音指令处理器处理识别结果
        if (voiceCommandHandler) {
          const commandResult = voiceCommandHandler.processVoiceCommand(result.text, result.is_final || false)
          
          if (commandResult.commandDetected) {
            // 检测到指令，执行相应的操作
            if (commandResult.shouldExecuteAction && commandResult.action) {
              await commandResult.action()
            }
          } else {
            // 没有检测到指令，正常处理语音识别结果
            if (result.is_final) {
              if (inputText.value) {
                inputText.value += ' ' + result.text
              } else {
                inputText.value = result.text
              }
              currentRecognitionText.value = ''
              
              // 显示识别完成的消息
              ElMessage.success({
                message: `✅ 识别完成: "${result.text}"`,
                duration: 2000
              })
            }
          }
        } else {
          // 语音指令处理器未初始化，使用默认处理
          if (result.is_final) {
            if (inputText.value) {
              inputText.value += ' ' + result.text
            } else {
              inputText.value = result.text
            }
            currentRecognitionText.value = ''
            
            // 显示识别完成的消息
            ElMessage.success({
              message: `✅ 识别完成: "${result.text}"`,
              duration: 2000
            })
          }
        }
      }
      break
      
    case 'recognition_started':
      ElMessage.info('🎙️ 语音识别已启动')
      break
      
    case 'recognition_ended':
      ElMessage.info('⏹️ 语音识别已结束')
      break
      
    case 'recognition_complete':
      ElMessage.success('✅ 语音识别完成')
      // 识别完成时，自动停止录音并重置状态
      resetAudioState()
      break
      
    case 'error':
      ElMessage.error(`❌ 识别错误: ${result.message}`)
      break
  }
}

const handleAudioError = (error: string) => {
  console.error('音频错误:', error)
  ElMessage.error(`🔴 音频错误: ${error}`)
  isRecording.value = false
  audioStatus.value = 'error'
}

const handleAudioStatusChange = (status: 'connecting' | 'connected' | 'recording' | 'stopped' | 'error') => {
  console.log('🔄 音频状态变化:', status)
  audioStatus.value = status
  
  switch (status) {
    case 'connecting':
      console.log('🔗 正在连接音频服务...')
      break
      
    case 'connected':
      console.log('✅ 音频服务已连接')
      // 连接成功时，确保连接状态被重置
      isConnectingAudio.value = false
      break
      
    case 'recording':
      console.log('🎤 开始录音')
      isRecording.value = true
      isConnectingAudio.value = false
      break
      
    case 'stopped':
      console.log('⏹️ 录音已停止')
      // 停止时重置所有相关状态
      isRecording.value = false
      isConnectingAudio.value = false
      currentRecognitionText.value = ''
      // 如果WebSocket连接正常，保持连接状态，方便下次录音
      if (audioClient.value && audioClient.value.getConnectionStatus() === 'connected') {
        audioStatus.value = 'connected'
      }
      break
      
    case 'error':
      console.log('❌ 音频服务出错')
      // 错误时重置所有状态
      isRecording.value = false
      isConnectingAudio.value = false
      currentRecognitionText.value = ''
      break
  }
  
  console.log('📊 当前状态:', {
    audioStatus: audioStatus.value,
    isRecording: isRecording.value,
    isConnectingAudio: isConnectingAudio.value,
    hasRecognitionText: !!currentRecognitionText.value
  })
}

const getVoiceButtonType = () => {
  if (!audioSupport.value.supported) {
    return 'info'
  }
  if (isRecording.value) {
    return 'danger'
  }
  if (audioStatus.value === 'connected') {
    return 'success'
  }
  if (audioStatus.value === 'error') {
    return 'danger'
  }
  return 'primary'
}

const handleButtonClick = (button: ButtonConfig) => {
  ElMessage.info(`点击了按钮：${button.text}，动作：${button.action}`)
  
  // 可以根据按钮的action执行不同的操作
  switch (button.action) {
    case 'clear':
      messages.value = []
      break
    case 'help':
      messages.value.push({
        type: 'assistant',
        content: '这里是帮助信息...',
        timestamp: new Date()
      })
      break
    default:
      messages.value.push({
        type: 'assistant',
        content: `执行了${button.text}操作`,
        timestamp: new Date()
      })
  }
  
  scrollToBottom()
}

const formatTime = (date: Date): string => {
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

const scrollToBottom = () => {
  if (messageListRef.value) {
    messageListRef.value.scrollTop = messageListRef.value.scrollHeight
  }
}

const toggleResultDisplay = (messageIndex: number, resultType: string) => {
  const message = messages.value[messageIndex]
  if (message) {
    message.showResult = !message.showResult
  }
}

// 键盘事件处理
const handleKeyDown = (event: KeyboardEvent) => {
  // Enter键处理
  if (event.key === 'Enter') {
    // Shift+Enter: 换行（默认行为）
    if (event.shiftKey) {
      return // 允许默认的换行行为
    }
    
    // 单独按Enter: 发送消息或确认交互
    event.preventDefault()
    
    if (isInInteractionMode.value) {
      // 交互模式：Enter键确认执行
      if (currentInteractionId.value) {
        respondToInteraction(true)
      }
    } else {
      // 普通模式：Enter键发送消息
      if (inputText.value.trim()) {
        sendMessage()
      }
    }
  }
  
  // Ctrl+Enter: 强制发送（在任何模式下）
  else if (event.ctrlKey && event.key === 'Enter') {
    event.preventDefault()
    if (!isInInteractionMode.value && inputText.value.trim()) {
      sendMessage()
    }
  }
  
  // Escape键: 取消交互模式
  else if (event.key === 'Escape' && isInInteractionMode.value) {
    event.preventDefault()
    if (currentInteractionId.value) {
      respondToInteraction(false)
    }
  }
}

// 新的人机交互响应方法
const respondToInteraction = async (approved: boolean) => {
  console.log('🔍 respondToInteraction 开始执行');

  if (!currentInteractionId.value) {
    ElMessage.error('没有有效的交互ID');
    console.error('❌ 没有有效的交互ID');
    return;
  }

  const interaction_id = currentInteractionId.value;
  const message = inputText.value.trim(); // 获取用户在输入框中的内容
  
  console.log('🔍 处理交互响应参数:', { interaction_id, approved, message });
  
  // 如果用户输入了补充消息，先将其显示在聊天框中
  if (message) {
    messages.value.push({
      type: 'user',
      content: message,
      timestamp: new Date()
    });
    
    // 滚动到底部显示用户消息
    await nextTick();
    scrollToBottom();
  }
  
  // 找到对应的交互消息
  const interactionMessage = messages.value.find(
    msg => msg.messageType === 'human_interaction' && 
           msg.data?.interaction_id === interaction_id
  );
  
  console.log('🔍 找到的交互消息:', interactionMessage);
  
  if (!interactionMessage) {
    ElMessage.error('未找到对应的交互消息');
    console.error('❌ 未找到对应的交互消息');
    return;
  }
  
  // 防止重复点击
  if (interactionMessage.data.responding || interactionMessage.data.responded) {
    return;
  }
  
  // 更新消息状态 - 显示加载状态
  interactionMessage.data.responding = true;
  interactionMessage.data.responded = true;
  interactionMessage.data.approved = approved;

  // 保存当前状态，稍后使用
  const originalInputText = inputText.value.trim();
  
  // 用户已做出决定，立即恢复输入框状态
  inputText.value = '';
  isInInteractionMode.value = false;
  currentInteractionId.value = null;
  console.log('✅ 用户已做出决定，立即恢复输入框状态');

  try {
    // 使用合并后的流式接口，传递message参数
    const eventSource = agentApi.handleHumanInteractionResponse(interaction_id, approved, originalInputText);
    
    // 设置超时处理
    const timeout = setTimeout(() => {
      if (eventSource && eventSource.readyState !== EventSource.CLOSED) {
        console.warn('人机交互响应超时，关闭连接');
        eventSource.close();
        ElMessage.warning('响应超时，请刷新页面重试');
      }
    }, 300000); // 5分钟超时
    
    eventSource.onmessage = async (event) => {
      try {
        const data = JSON.parse(event.data);
        console.log('人机交互响应消息:', data);
        
        // 处理不同类型的消息
        await handleStreamMessage(data);
        
        // 如果收到完成信号，清理资源
        if (data.type === 'done' || data.type === 'final_result') {
          clearTimeout(timeout);
          if (eventSource) {
            eventSource.close();
          }
          
          console.log('✅ 人机交互任务完成');
        }
        
      } catch (parseError: any) {
        console.error('解析响应消息失败:', parseError);
        ElMessage.error('消息解析失败');
      }
    };

    eventSource.onerror = (error: any) => {
      console.error('人机交互响应流出现错误:', error);
      clearTimeout(timeout);
      
      // 恢复消息状态
      interactionMessage.data.responding = false;
      interactionMessage.data.responded = false;
      
      if (eventSource) {
        eventSource.close();
      }
      
      // 根据错误类型提供不同的提示
      if (eventSource?.readyState === EventSource.CONNECTING) {
        ElMessage.error('连接服务器失败，请检查网络连接');
      } else {
        ElMessage.error('响应处理中断，请刷新页面重试');
      }
    };

    eventSource.onopen = () => {
      console.log('人机交互响应连接已建立');
      // 连接成功后，隐藏加载状态
      interactionMessage.data.responding = false;
      
      // 显示成功消息（只显示一次）
      if (!interactionMessage.data.confirmationShown) {
        ElMessage.success(approved ? '✅ 已确认执行' : '❌ 已取消执行');
        interactionMessage.data.confirmationShown = true;
      }
    };

  } catch (error: any) {
    console.error('启动人机交互响应失败:', error);
    
    // 恢复消息状态
    interactionMessage.data.responding = false;
    interactionMessage.data.responded = false;
    
    ElMessage.error({
      message: '操作失败: ' + (error.message || '未知错误'),
      duration: 5000,
      showClose: true
    });
  }
}


// TTS 相关方法
const playTTSAudio = async (text: string) => {
  if (!isTTSEnabled.value || !text.trim()) {
    return
  }

  try {
    // 停止当前播放的音频
    stopCurrentAudio()

    console.log('🔊 开始TTS合成:', text.substring(0, 50) + '...')
    isPlayingTTS.value = true

    // 调用TTS API
    const result = await audioAPI.tts.synthesizeToBase64(text)
    
    if (result.success && result.data_url) {
      // 创建音频元素并播放
      const audio = new Audio(result.data_url)
      currentAudio.value = audio

      // 设置音频事件监听
      audio.onloadstart = () => {
        console.log('🎵 音频开始加载')
      }

      audio.oncanplaythrough = () => {
        console.log('✅ 音频加载完成，开始播放')
        audio.play().catch(error => {
          console.error('播放音频失败:', error)
          ElMessage.error('播放语音失败')
          isPlayingTTS.value = false
        })
      }

      audio.onended = () => {
        console.log('🎵 音频播放完成')
        isPlayingTTS.value = false
        currentAudio.value = null
      }

      audio.onerror = (error) => {
        console.error('音频播放错误:', error)
        ElMessage.error('语音播放出错')
        isPlayingTTS.value = false
        currentAudio.value = null
      }

      // 显示播放提示
      ElMessage.success({
        message: '🎵 开始播放语音',
        duration: 1000
      })

    } else {
      throw new Error('TTS合成失败')
    }

  } catch (error: any) {
    console.error('TTS播放失败:', error)
    ElMessage.error(`语音播放失败: ${error.message || '未知错误'}`)
    isPlayingTTS.value = false
  }
}

const stopCurrentAudio = () => {
  if (currentAudio.value) {
    currentAudio.value.pause()
    currentAudio.value.currentTime = 0
    currentAudio.value = null
  }
  isPlayingTTS.value = false
}

const toggleTTS = () => {
  isTTSEnabled.value = !isTTSEnabled.value
  ElMessage.info(isTTSEnabled.value ? '✅ TTS已启用' : '❌ TTS已禁用')
  
  // 如果禁用TTS，停止当前播放
  if (!isTTSEnabled.value) {
    stopCurrentAudio()
  }
}

// TTS设置相关方法
const showTTSSettingsMenu = (event: MouseEvent) => {
  showTTSSettings.value = true
}

const handleTTSSettingsChanged = (newSettings: TTSConfig) => {
  Object.assign(ttsSettings.value, newSettings)
  console.log('TTS设置已更新:', newSettings)
}

const saveTTSSettings = () => {
  try {
    localStorage.setItem('tts-settings', JSON.stringify(ttsSettings.value))
  } catch (error) {
    console.warn('保存TTS设置失败:', error)
  }
}

const loadTTSSettings = () => {
  try {
    const saved = localStorage.getItem('tts-settings')
    if (saved) {
      const settings = JSON.parse(saved)
      ttsSettings.value = { ...ttsSettings.value, ...settings }
    }
  } catch (error) {
    console.warn('加载TTS设置失败:', error)
  }
}

// 处理流消息（从继续执行和普通消息流中复用）
const handleStreamMessage = async (streamData: any) => {
  const { type, content, timestamp, data } = streamData
      
  switch (type) {
    case 'thinking':
      // 思考消息 - 每次都创建新的消息，保持独立性
      messages.value.push({
        type: 'assistant',
        content: content,
        timestamp: new Date(timestamp),
        messageType: 'thinking',
        data: data
      })
      break
      
    case 'message':
    // AI回复消息
    if (data?.partial === false) {
      // 最终完整消息，如果有之前的部分消息则替换
      const lastMessage = messages.value[messages.value.length - 1]
      if (lastMessage && lastMessage.type === 'assistant' && lastMessage.messageType === 'message' && lastMessage.partial) {
        lastMessage.content = content
        lastMessage.partial = false
        lastMessage.data = data
      } else {
        messages.value.push({
          type: 'assistant',
          content: content,
          timestamp: new Date(timestamp),
          messageType: 'message',
          data: data,
          partial: false
        })
      }
     
    } else {
      // 部分消息（流式输出）
      const lastMessage = messages.value[messages.value.length - 1]
      if (lastMessage && lastMessage.type === 'assistant' && lastMessage.messageType === 'message' && lastMessage.partial) {
        // 更新现有的部分消息
        lastMessage.content = content
        lastMessage.data = data
      } else {
        // 创建新的部分消息
        messages.value.push({
          type: 'assistant',
          content: content,
          timestamp: new Date(timestamp),
          messageType: 'message',
          data: data,
          partial: true
        })
      }
    }
    break
    
  case 'tool':
    // 工具调用消息
    messages.value.push({
      type: 'assistant',
      content: content,
      timestamp: new Date(timestamp),
      messageType: 'tool',
      data: data
    })
    break
    
  case 'rag':
    // RAG检索消息
    messages.value.push({
      type: 'assistant',
      content: content,
      timestamp: new Date(timestamp),
      messageType: 'rag',
      data: data
    })
    break
    
  case 'error':
    // 错误消息
    messages.value.push({
      type: 'assistant',
      content: content,
      timestamp: new Date(timestamp),
      messageType: 'error',
      data: data
    })
    break
    
  case 'mcp':
    // MCP接口消息
    messages.value.push({
      type: 'assistant',
      content: content,
      timestamp: new Date(timestamp),
      messageType: 'mcp',
      data: data
    })
    break
    
  case 'human_interaction':
    console.log('🔍 收到human_interaction消息:', { content, data });
    
    // 人机交互消息 - 检查是否已存在相同的交互ID
    const existingInteraction = messages.value.find(
      msg => msg.messageType === 'human_interaction' && 
             msg.data?.interaction_id === data?.interaction_id
    );
    
    console.log('🔍 检查重复交互消息:', {
      interaction_id: data?.interaction_id,
      existingInteraction: !!existingInteraction
    });
    
    if (!existingInteraction) {
      // 只有当不存在相同交互ID的消息时才添加
      messages.value.push({
        type: 'assistant',
        content: content,
        timestamp: new Date(timestamp),
        messageType: 'human_interaction',
        data: {
          ...data,
          responded: false,
          responding: false
        }
      })
      
      console.log('🔍 设置交互状态:', {
        currentInteractionId_before: currentInteractionId.value,
        isInInteractionMode_before: isInInteractionMode.value,
        new_interaction_id: data?.interaction_id
      });
      
      // 立即进入人机交互模式
      currentInteractionId.value = data?.interaction_id;
      isInInteractionMode.value = true;
      
      console.log('🔍 交互状态已更新:', {
        currentInteractionId_after: currentInteractionId.value,
        isInInteractionMode_after: isInInteractionMode.value
      });
      
      // 使用nextTick确保状态更新完成后再显示提示
      await nextTick();
      
      // 再次验证状态是否正确设置
      console.log('🔍 nextTick后的交互状态:', {
        currentInteractionId_final: currentInteractionId.value,
        isInInteractionMode_final: isInInteractionMode.value
      });
      
    } else {
      console.log('🔍 跳过重复的人机交互消息:', data?.interaction_id);
    }
    break
    
  case 'final_result':
    // 最终结果消息
    messages.value.push({
      type: 'assistant',
      content: data?.response || content,
      timestamp: new Date(timestamp),
      messageType: 'message',
      data: {
        ...data,
        partial: false,
        final: true,
        isFinalResult: true
      }
    })
    console.log('🎵 isTTSEnabled.value:', isTTSEnabled.value)
      // 🎵 AI回复完成时自动播放TTS
      if (isTTSEnabled.value && content.trim()) {
        // 延迟一点播放，确保消息已显示
        setTimeout(() => {
          console.log('🎵 开始播放TTS音频:', content)
          playTTSAudio(content)
        }, 500)
      }
    break
    
  case 'done':
    // 流结束
    console.log('消息流结束')
    // 交互状态已经在用户点击确认/取消时清理，这里不需要额外处理
    break
  }
  
  // 滚动到底部
  nextTick(() => scrollToBottom())
}

// 监听来自父窗口的消息
const handleMessage = (event: MessageEvent) => {
  if (event.origin !== window.location.origin) return
  
  const { type, data } = event.data
  switch (type) {
    case 'test':
      messages.value.push({
        type: 'assistant',
        content: `收到来自主窗口的消息: ${data.message}`,
        timestamp: new Date()
      })
      scrollToBottom()
      break
  }
}

// 生命周期
onMounted(() => {
  loadDialogConfig()
  window.addEventListener('message', handleMessage)
  
  // 检查音频支持（在mounted时也检查一次）
  console.log('ChatWindow mounted, 检查音频支持:', audioSupport.value)
  
  // 加载TTS设置
  loadTTSSettings()
  
  // 初始化语音指令处理器
  const voiceCommandConfig: VoiceCommandHandlerConfig = {
    inputText,
    currentRecognitionText,
    sendMessage,
    stopRecording,
    clearScreen,
    respondToInteraction,  // 人机交互响应方法
    isInInteractionMode  // 添加人机交互状态
  }
  voiceCommandHandler = new VoiceCommandHandler(voiceCommandConfig)
  
  // 加载场景选项
  loadSceneOptions()
  
  // 设置窗口标题
  document.title = 'AI智能对话'
})

// 组件卸载时清理资源
onUnmounted(() => {
  window.removeEventListener('message', handleMessage)
  
  // 清理音频客户端
  if (audioClient.value) {
    audioClient.value.disconnect()
    audioClient.value = null
  }
  
  // 清理TTS音频
  stopCurrentAudio()
})

// 显示快捷键帮助
const showKeyboardHelp = () => {
  KeyboardHelpUtils.showHelpByMode(isRecording.value, isInInteractionMode.value)
}
</script>

<style scoped>
.chat-window {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chat-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  flex-shrink: 0;
}

.header-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-scene-selector {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-left: 8px;
}

.scene-separator {
  color: rgba(255, 255, 255, 0.7);
  font-weight: 300;
  font-size: 14px;
}

.scene-select {
  width: 150px;
}

.scene-select :deep(.el-input__wrapper) {
  background-color: rgba(255, 255, 255, 0.15);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 6px;
  box-shadow: none;
  transition: all 0.3s ease;
}

.scene-select :deep(.el-input__wrapper):hover {
  background-color: rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.5);
}

.scene-select :deep(.el-input__wrapper.is-focus) {
  background-color: rgba(255, 255, 255, 0.25);
  border-color: rgba(255, 255, 255, 0.7);
  box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.1);
}

.scene-select :deep(.el-input__inner) {
  color: white;
  font-size: 13px;
  font-weight: 400;
}

.scene-select :deep(.el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.6);
  font-size: 12px;
}

.scene-select :deep(.el-input__suffix) {
  color: rgba(255, 255, 255, 0.8);
}

.scene-select :deep(.el-select__caret) {
  color: rgba(255, 255, 255, 0.8);
}

/* 场景选择器下拉选项样式 */
:deep(.el-select-dropdown__item) {
  padding: 6px 12px;
  font-size: 13px;
  line-height: 1.4;
}

/* 父场景选项样式 */
:deep(.el-select-dropdown__item:has-text("↑")) {
  color: #909399;
  font-style: italic;
}

/* 当前场景选项样式 */
:deep(.el-select-dropdown__item:has-text("●")) {
  color: #409eff;
  font-weight: 500;
  background-color: rgba(64, 158, 255, 0.1);
}

/* 子场景选项样式 */
:deep(.el-select-dropdown__item:has-text("↓")) {
  color: #67c23a;
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-tts-btn {
  width: 32px;
  height: 32px;
  min-height: 32px;
  background-color: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s ease;
}

.header-tts-btn:hover {
  background-color: rgba(255, 255, 255, 0.3);
  transform: scale(1.05);
}

.header-tts-btn.el-button--success {
  background-color: rgba(103, 194, 58, 0.8);
  border-color: rgba(103, 194, 58, 0.9);
}

.header-tts-btn.el-button--info {
  background-color: rgba(144, 147, 153, 0.6);
  border-color: rgba(144, 147, 153, 0.8);
}

.header-clear-btn {
  width: 32px;
  height: 32px;
  min-height: 32px;
  background-color: rgba(245, 108, 108, 0.8);
  border: 1px solid rgba(245, 108, 108, 0.9);
  transition: all 0.3s ease;
}

.header-clear-btn:hover {
  background-color: rgba(245, 108, 108, 0.9);
  transform: scale(1.05);
}

.header-tts-indicator {
  color: #fff;
  font-size: 16px;
  font-weight: bold;
  animation: pulse 1s infinite;
  text-shadow: 0 0 4px rgba(255, 255, 255, 0.5);
}

.title {
  font-weight: 600;
  font-size: 14px;
}

.message-list {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background: white;
}

.message-item {
  margin-bottom: 16px;
  display: flex;
}

.message-item.user {
  justify-content: flex-end;
}

.message-item.assistant {
  justify-content: flex-start;
}

.message-content {
  max-width: 80%;
  padding: 8px 12px;
  border-radius: 8px;
  position: relative;
}

.message-item.user .message-content {
  background: #4facfe;
  color: white;
}

.message-item.assistant .message-content {
  background: #f0f2f5;
  color: #333;
}

/* 不同消息类型的样式 */
.message-item.assistant.thinking .message-content {
  background: #f8f9fa;
  border-left: 3px solid #d0d7de;
  opacity: 0.85;
}

.message-item.assistant.tool .message-content {
  background: #fff7e6;
  border-left: 3px solid #fa8c16;
}

.message-item.assistant.rag .message-content {
  background: #f6ffed;
  border-left: 3px solid #52c41a;
}

.message-item.assistant.mcp .message-content {
  background: #f0f2f5;
  border-left: 3px solid #8c8c8c;
}

.message-item.assistant.human_interaction .message-content {
  background: #fffbf0;
  border-left: 3px solid #faad14;
}

.message-item.assistant.error .message-content {
  background: #fff2f0;
  border-left: 3px solid #ff4d4f;
}

.message-text {
  margin-bottom: 4px;
}

.message-time {
  font-size: 12px;
  opacity: 0.7;
}

.input-area {
  padding: 16px;
  border-top: 1px solid #e0e0e0;
  background: white;
  display: flex;
  flex-direction: column;
  gap: 8px;
  flex-shrink: 0;
}

.mode-indicators {
  display: flex;
  gap: 4px;
  margin-bottom: 8px;
}



.input-with-send {
  display: flex;
  align-items: flex-end;
  gap: 12px;
}

.text-input {
  flex: 1;
  position: relative;
}

.input-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  position: absolute;
  right: 12px;
  top: 12px;
  z-index: 10;
}

.voice-btn {
  width: 28px;
  height: 28px;
  min-height: 28px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.tts-btn {
  width: 28px;
  height: 28px;
  min-height: 28px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-left: 8px;
}

.recording-indicator {
  color: #f56c6c;
  font-size: 14px;
  font-weight: bold;
  animation: pulse 1s infinite;
}

.audio-status {
  font-size: 12px;
  margin-left: 8px;
  color: #909399;
}

.audio-status.connected {
  color: #67c23a;
}

.audio-status.error {
  color: #f56c6c;
}

.recognition-preview {
  position: absolute;
  top: -35px;
  left: 12px;
  right: 12px;
  background: #f0f9ff;
  border: 1px solid #91d5ff;
  border-radius: 6px;
  padding: 8px 12px;
  font-size: 13px;
  z-index: 10;
}

.recognition-label {
  color: #1890ff;
  font-weight: 500;
  margin-right: 8px;
}

.recognition-text {
  color: #262626;
  font-style: italic;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

/* 思考动画 */
.thinking-dots {
  display: inline-block;
  position: relative;
  color: #666;
  font-style: italic;
}

.thinking-dots::after {
  content: '';
  animation: thinking 1.5s infinite;
}

@keyframes thinking {
  0% { content: ''; }
  25% { content: '.'; }
  50% { content: '..'; }
  75% { content: '...'; }
  100% { content: ''; }
}

/* 调整textarea的右边距，为按钮留出空间 */
.text-input :deep(.el-textarea__inner) {
  padding-right: 40px !important;
  resize: none;
}

/* 人机交互相关样式 */
.interaction-input :deep(.el-textarea__inner) {
  border: 2px solid #faad14 !important;
  background-color: #fffbf0 !important;
  box-shadow: 0 0 0 2px rgba(250, 173, 20, 0.2) !important;
}

.interaction-prompt {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
  padding: 10px 12px;
  background: linear-gradient(90deg, #fff7e6 0%, #fffbf0 100%);
  border: 1px solid #ffd666;
  border-radius: 8px;
  color: #ad6800;
  font-size: 14px;
  box-shadow: 0 2px 4px rgba(250, 173, 20, 0.1);
}

.prompt-icon {
  color: #faad14;
  font-size: 18px;
  animation: bounce 2s infinite;
}

.prompt-text {
  flex: 1;
  line-height: 1.5;
  font-weight: 500;
}

.interaction-buttons {
  display: flex;
  flex-direction: column;
  gap: 10px;
  min-width: 130px;
}

.interaction-buttons .el-button {
  margin: 0;
  border-radius: 8px;
  font-weight: 600;
  font-size: 14px;
  padding: 12px 16px;
  transition: all 0.3s ease;
}

.interaction-buttons .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.send-button {
  display: flex;
  align-items: flex-end;
}

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-4px);
  }
  60% {
    transform: translateY(-2px);
  }
}

.voice-input, .video-input {
  display: flex;
  align-items: center;
  gap: 8px;
}

.recording-text {
  color: #f56c6c;
  font-size: 12px;
  animation: pulse 1s infinite;
}

.custom-buttons {
  padding: 0 16px 16px;
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  background: white;
  flex-shrink: 0;
}

.error-container {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
}

/* 滚动条样式 */
.message-list::-webkit-scrollbar {
  width: 6px;
}

.message-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.message-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.message-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.message-icon {
  margin-right: 8px;
}

.tool-text {
  color: #333;
}

.tool-indicator {
  margin-right: 4px;
}

.tool-result {
  margin-top: 4px;
  font-size: 12px;
  opacity: 0.7;
}

.tool-data {
  margin-top: 4px;
  font-size: 12px;
}

.tool-data details {
  margin-top: 4px;
}

.tool-data summary {
  cursor: pointer;
  color: #1890ff;
  font-size: 11px;
}

.tool-data pre {
  background: #f5f5f5;
  padding: 8px;
  border-radius: 4px;
  font-size: 10px;
  max-height: 200px;
  overflow-y: auto;
  margin-top: 4px;
}

.rag-text {
  color: #333;
}

.rag-indicator {
  margin-right: 4px;
}

.rag-info {
  margin-top: 4px;
  font-size: 12px;
  opacity: 0.7;
}

.rag-data {
  margin-top: 4px;
  font-size: 12px;
}

.rag-data details {
  margin-top: 4px;
}

.rag-data summary {
  cursor: pointer;
  color: #1890ff;
  font-size: 11px;
}

.rag-data pre {
  background: #f5f5f5;
  padding: 8px;
  border-radius: 4px;
  font-size: 10px;
  max-height: 200px;
  overflow-y: auto;
  margin-top: 4px;
}

.mcp-text {
  color: #8c8c8c;
}

.mcp-indicator {
  margin-right: 4px;
}

.mcp-result {
  margin-top: 4px;
  font-size: 12px;
  opacity: 0.7;
}

.mcp-data {
  margin-top: 4px;
  font-size: 12px;
}

.mcp-data details {
  margin-top: 4px;
}

.mcp-data summary {
  cursor: pointer;
  color: #1890ff;
  font-size: 11px;
}

.mcp-data pre {
  background: #f5f5f5;
  padding: 8px;
  border-radius: 4px;
  font-size: 10px;
  max-height: 200px;
  overflow-y: auto;
  margin-top: 4px;
}

.thinking-text {
  color: #6b7280;
  font-size: 13px;
  font-style: italic;
  line-height: 1.4;
}

.thinking-indicator {
  margin-right: 6px;
  opacity: 0.7;
}

.error-text {
  color: #f56c6c;
}

.error-indicator {
  margin-right: 4px;
}

.typing-cursor {
  animation: blink 0.7s step-end infinite;
}

@keyframes blink {
  from, to {
    color: transparent;
  }
  50% {
    color: #333;
  }
}

/* Markdown样式 - 适配marked库 */
.message-text :deep(h1),
.message-text :deep(h2),
.message-text :deep(h3),
.message-text :deep(h4),
.message-text :deep(h5),
.message-text :deep(h6) {
  margin: 12px 0 8px 0;
  font-weight: 600;
  line-height: 1.4;
}

.message-text :deep(h1) {
  font-size: 20px;
  color: #2c3e50;
  border-bottom: 2px solid #3498db;
  padding-bottom: 6px;
}

.message-text :deep(h2) {
  font-size: 18px;
  color: #34495e;
  border-bottom: 1px solid #bdc3c7;
  padding-bottom: 4px;
}

.message-text :deep(h3) {
  font-size: 16px;
  color: #7f8c8d;
}

.message-text :deep(h4) {
  font-size: 14px;
  color: #95a5a6;
}

.message-text :deep(h5),
.message-text :deep(h6) {
  font-size: 13px;
  color: #95a5a6;
}

.message-text :deep(p) {
  margin: 8px 0;
  line-height: 1.5;
}

.message-text :deep(strong) {
  font-weight: 600;
  color: #2c3e50;
}

.message-text :deep(em) {
  font-style: italic;
  color: #7f8c8d;
}

.message-text :deep(code) {
  background: #f8f9fa;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
  color: #e74c3c;
  border: 1px solid #e9ecef;
}

.message-text :deep(pre) {
  background: #2d3748;
  color: #e2e8f0;
  padding: 16px;
  border-radius: 8px;
  margin: 12px 0;
  overflow-x: auto;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.5;
  border: 1px solid #4a5568;
}

.message-text :deep(pre code) {
  background: none;
  padding: 0;
  border: none;
  color: inherit;
  font-size: inherit;
}

.message-text :deep(ul),
.message-text :deep(ol) {
  margin: 8px 0;
  padding-left: 24px;
}

.message-text :deep(li) {
  margin: 4px 0;
  line-height: 1.5;
}

.message-text :deep(li p) {
  margin: 2px 0;
}

.message-text :deep(a) {
  color: #3498db;
  text-decoration: none;
  border-bottom: 1px solid transparent;
  transition: all 0.2s ease;
}

.message-text :deep(a:hover) {
  color: #2980b9;
  border-bottom-color: #2980b9;
}

.message-text :deep(blockquote) {
  border-left: 4px solid #3498db;
  margin: 12px 0;
  padding: 12px 16px;
  background: #f8f9fa;
  border-radius: 0 6px 6px 0;
  color: #7f8c8d;
  font-style: italic;
}

.message-text :deep(blockquote p) {
  margin: 0;
}

.message-text :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin: 12px 0;
  font-size: 13px;
}

.message-text :deep(table th),
.message-text :deep(table td) {
  border: 1px solid #ddd;
  padding: 8px 12px;
  text-align: left;
}

.message-text :deep(table th) {
  background-color: #f2f2f2;
  font-weight: 600;
}

.message-text :deep(table tr:nth-child(even)) {
  background-color: #f9f9f9;
}

.message-text :deep(hr) {
  border: none;
  border-top: 2px solid #e9ecef;
  margin: 16px 0;
}

/* 确保markdown内容在消息中正确显示 */
.message-text {
  word-wrap: break-word;
  word-break: break-word;
  overflow-wrap: break-word;
}

/* 代码语法高亮的基础样式 */
.message-text :deep(.language-javascript),
.message-text :deep(.language-js) {
  color: #f8c555;
}

.message-text :deep(.language-python) {
  color: #3776ab;
}

.message-text :deep(.language-html) {
  color: #e34c26;
}

.message-text :deep(.language-css) {
  color: #1572b6;
}

/* 最终结果消息特殊样式 */
.message-item.assistant .message-content[data-final="true"] {
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
  border-left: 4px solid #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.15);
  position: relative;
  margin-top: 8px;
}

/* 结果展示按钮和内容样式 */
.tool-result-section,
.rag-result-section,
.mcp-result-section {
  margin-top: 8px;
}

.result-toggle-btn {
  margin-top: 4px;
  font-size: 12px;
  height: 24px;
  padding: 0 8px;
}

.result-content {
  margin-top: 8px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 12px;
  max-height: 300px;
  overflow-y: auto;
}

.result-content pre {
  margin: 0;
  background: none;
  border: none;
  padding: 0;
  font-size: 12px;
  line-height: 1.4;
  color: #495057;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.interaction-text {
  color: #333;
}

.interaction-content {
  margin-bottom: 8px;
}

.interaction-question {
  margin-bottom: 8px;
}

.tool-info {
  margin-bottom: 8px;
}

.tool-info h4 {
  margin-bottom: 4px;
  font-weight: 600;
}

.tool-info p {
  margin: 4px 0;
}

.parameters {
  margin-top: 4px;
}

.params-preview {
  background: #f8f9fa;
  padding: 4px;
  border-radius: 4px;
  font-size: 12px;
}

.interaction-buttons {
  margin-top: 8px;
  display: flex;
  gap: 8px;
}

.interaction-result {
  margin-top: 8px;
}

.tts-indicator {
  color: #67c23a;
  font-size: 14px;
  font-weight: bold;
  animation: pulse 1s infinite;
  margin-left: 4px;
}

/* 快捷键帮助按钮样式 */
.keyboard-help-container {
  display: flex;
  justify-content: flex-end;
  padding: 0 4px 8px 0;
}

.keyboard-help-btn {
  font-size: 12px;
  height: 24px;
  padding: 0 8px;
  border-radius: 12px;
  transition: all 0.3s ease;
  opacity: 0.8;
}

.keyboard-help-btn:hover {
  opacity: 1;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.keyboard-help-btn .el-icon {
  margin-right: 4px;
  font-size: 14px;
}

.interaction-waiting {
  margin-top: 8px;
  padding: 4px 0;
}

.interaction-waiting .el-tag {
  animation: pulse 2s infinite;
}

.interaction-result {
  margin-top: 8px;
}


</style> 